package Ppackage;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class Buffer
{
    private Queue<Product> queue = new LinkedList<>();
    private final int capacity = 4;
    private final Lock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();
    private int nextId = 0;

    public void produce(int count) throws InterruptedException
    {
        lock.lock();
        try
        {
            while (queue.size() + count > capacity)
            {
                System.out.println(Thread.currentThread().getName() + " 等待放产品");
                notFull.await();
            }
            for (int i = 0; i < count; i++)
            {
                Product product = new Product(nextId++);
                queue.add(product);
            }
            System.out.println(Thread.currentThread().getName() + " 放" + count + "个 产品");
            notEmpty.signalAll();
        }
        finally
        {
            lock.unlock();
        }
    }

    public Product consume() throws InterruptedException
    {
        lock.lock();
        try
        {
            while (queue.isEmpty())
            {
                System.out.println(Thread.currentThread().getName() + " 等待取产品");
                notEmpty.await();
            }
            Product product = queue.poll();
            System.out.println(Thread.currentThread().getName() + " 取产品使用 ");
            notFull.signalAll();
            return product;
        }
        finally
        {
            lock.unlock();
        }
    }
}
